const connection = require("../app/database");
class BaseService {
  constructor(tableName) {
    this.tableName = tableName;
  }
  async saveOrUpdate(obj) {
    let keyArray = [];
    let valueArray = [];
    let hasId = false;
    for (let key in obj) {
      //如果是undefined,就给删掉
      if (!obj[key] === undefined) {
        delete obj[key];
        continue;
      }
      if (key === "id") {
        hasId = true;
      }
      //收集key
      keyArray.push(key);
      //收集value
      valueArray.push(obj[key]);
    }
    if (hasId) {
      //有id，执行update
      //1.拼接sql
      let sql = `UPDATE ${this.tableName} SET `;
      for (let i = 0; i < keyArray.length; i++) {
        sql += `${keyArray[i]} = ?,`;
      }
      sql = sql.substring(0, sql.length - 1);
      sql += ` WHERE id = ?`;
      return await connection.execute(sql, [...valueArray, obj.id]);
    } else {
      //没有id，执行insert
      //1.拼接sql
      let sql = `INSERT INTO ${this.tableName} (`;
      for (let i = 0; i < keyArray.length; i++) {
        sql += `${keyArray[i]},`;
      }
      sql = sql.substring(0, sql.length - 1);
      sql += `) VALUES (`;
      for (let i = 0; i < valueArray.length; i++) {
        sql += `?,`;
      }
      sql = sql.substring(0, sql.length - 1);
      sql += `)`;
      return await connection.execute(sql, valueArray);
    }
  }
  async getById(id) {
    const statement = `SELECT * FROM ${this.tableName} WHERE id = ?;`;
    const [result] = await connection.execute(statement, [id]);
    return result.pop();
  }
  async getList(pageIndex, pageSize, queryCondition) {
    let queryConditionString = "";
    queryCondition.forEach((item) => {
      if (item.type == "like") {
        queryConditionString += `and ${item.key} like '%${item.value}%' `;
      } else {
        queryConditionString += `and ${item.key}='${item.value}' `;
      }
    });
    console.log(pageIndex, pageSize, queryCondition);
    let offset = (pageIndex - 1) * pageSize;
    const statement = `SELECT * FROM ${this.tableName} where 1=1  ${queryConditionString} LIMIT ?,?;`;
    const [result] = await connection.execute(statement, [
      offset + "",
      pageSize + "",
    ]);

    const total = await connection.execute(
      `SELECT COUNT(*) FROM ${this.tableName} where 1=1  ${queryConditionString};`
    );
    return {
      list: result,
      total: total[0][0]["COUNT(*)"],
    };

    //return result;
  }
  async deleteById(id) {
    const statement = `DELETE FROM ${this.tableName} WHERE id = ?;`;
    const [result] = await connection.execute(statement, [id]);
    return result;
  }
}
module.exports = BaseService;
